package com.zlsy.springbootdemo.classloader;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;

import java.io.*;
import java.util.Objects;

/**
 * @author zhouliang
 * @date 2021/1/10 13:09
 */
@Slf4j
public class MyClassLoader extends ClassLoader {

  private String myName;

  public MyClassLoader(String myName) {
    this.myName = myName;
  }

  @Override
  protected Class<?> findClass(String name) throws ClassNotFoundException {
    byte[] data = this.loadClassData(name);
    return this.defineClass(name, data, 0, data.length);
  }

  private byte[] loadClassData(String className) {
    byte[] data = null;

    InputStream in = null;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    className = className.replace(".", "/");
    try {
      String path =
          Objects.requireNonNull(
                  Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource(""))
              .getPath();
      String filePath = path + className + ".class";
      log.info("filePath ===>> \n {} ", filePath);
      in = new FileInputStream(new File(filePath));
      int a;
      while ((a = in.read()) != -1) {
        out.write(a);
      }
      data = out.toByteArray();
    } catch (IOException e) {
      log.error(e.getMessage(), e);
    } finally {
      if (Objects.nonNull(in)) {
        try {
          in.close();
        } catch (IOException e) {
          log.error(e.getMessage(), e);
        }
      }
    }
    return data;
  }
}
